package org.dromara.event.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.event.domain.EqpDevice;
import org.dromara.event.mapper.EqpDeviceMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.dromara.event.domain.bo.MaintenanceBo;
import org.dromara.event.domain.vo.MaintenanceVo;
import org.dromara.event.domain.Maintenance;
import org.dromara.event.mapper.MaintenanceMapper;
import org.dromara.event.service.IMaintenanceService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 报修管理Service业务层处理
 *
 * @author Yi LH
 * @date 2025-05-05
 */
@RequiredArgsConstructor
@Service
public class MaintenanceServiceImpl implements IMaintenanceService {

    private final MaintenanceMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final EqpDeviceMapper eqpDeviceMapper;

    private final ScheduledExecutorService scheduledExecutorService;

    /**
     * 查询报修管理
     *
     * @param id 主键
     * @return 报修管理
     */
    @Override
    public MaintenanceVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询报修管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 报修管理分页列表
     */
    @Override
    public TableDataInfo<MaintenanceVo> queryPageList(MaintenanceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Maintenance> lqw = buildQueryWrapper(bo);
        Page<MaintenanceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的报修管理列表
     *
     * @param bo 查询条件
     * @return 报修管理列表
     */
    @Override
    public List<MaintenanceVo> queryList(MaintenanceBo bo) {
        LambdaQueryWrapper<Maintenance> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Maintenance> buildQueryWrapper(MaintenanceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Maintenance> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(Maintenance::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getReporter()), Maintenance::getReporter, bo.getReporter());
        lqw.eq(StringUtils.isNotBlank(bo.getLocation()), Maintenance::getLocation, bo.getLocation());
        lqw.eq(StringUtils.isNotBlank(bo.getHandler()), Maintenance::getHandler, bo.getHandler());
        lqw.like(StringUtils.isNotBlank(bo.getEqpName()), Maintenance::getEqpName, bo.getEqpName());
        lqw.eq(StringUtils.isNotBlank(bo.getCompletionStatus()), Maintenance::getCompletionStatus, bo.getCompletionStatus());
        lqw.eq(bo.getCompletionTime() != null, Maintenance::getCompletionTime, bo.getCompletionTime());
        lqw.eq(bo.getReportTime() != null, Maintenance::getReportTime, bo.getReportTime());
        lqw.eq(StringUtils.isNotBlank(bo.getSourceType()), Maintenance::getSourceType, bo.getSourceType());
        return lqw;
    }

    /**
     * 新增报修管理
     *
     * @param bo 报修管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(MaintenanceBo bo) {
        Maintenance add = MapstructUtils.convert(bo, Maintenance.class);
        add.setReporter(sysUserMapper.selectVoById(LoginHelper.getUserId()).getNickName());
        add.setReporterId(LoginHelper.getUserId());
        add.setCreateBy(LoginHelper.getUserId());
        add.setCreateTime(new Date());
        add.setUpdateBy(LoginHelper.getUserId());
        add.setUpdateTime(new Date());
        add.setReportTime(new Date());
        add.setCompletionStatus("0");
        add.setHandler(sysUserMapper.selectVoById(1).getNickName());
        add.setHandlerId(1L);
        add.setSourceType("0");
        validEntityBeforeSave(add);
        scheduledExecutorService.schedule(() -> {
            SseMessageDto dto = new SseMessageDto();
            dto.setMessage("有新的设备需要维修！位于"+add.getLocation()+"的"+add.getEqpName()+"!");
            dto.setUserIds(List.of(1L));
            SseMessageUtils.publishMessage(dto);
        }, 5, TimeUnit.SECONDS);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改报修管理
     *
     * @param bo 报修管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MaintenanceBo bo) {
        Maintenance update = MapstructUtils.convert(bo, Maintenance.class);

        if (update.getCompletionStatus().equals("1")){
            EqpDevice eqpDevice = eqpDeviceMapper.selectById(update.getEqpId());
            eqpDevice.setStatus("0");
            update.setCompletionTime(new Date());
            eqpDeviceMapper.updateById(eqpDevice);
        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Maintenance entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除报修管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
